using System.Collections.Concurrent;

namespace Nova.Net;

using System.Collections.Generic;

public class ObjectPool<T> where T : new()
{
    private readonly ConcurrentQueue<T> pool; // 存储对象的队列

    public int Count => pool.Count; // 对象池中对象的数量

    public ObjectPool(int initialCapacity)
    {
        pool = new ConcurrentQueue<T>();
        Init(initialCapacity);
    }

    private void Init(int initialCapacity=10)
    {
        for (var i = 0; i < initialCapacity; i++)
        {
            pool.Enqueue(new T()); // 初始化时创建一定数量的对象放入池中
        }
    }

    public T GetObject()
    {
        return pool.TryDequeue(out var obj) ? obj : new T();
    }

    public void ReturnObject(T obj)
    {
        pool.Enqueue(obj); // 将不再使用的对象放回队列中
    }
}
